#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Author : fanzf
# @Version：V 0.1
# @desc :
import subprocess
import time
from flask import Blueprint, jsonify, current_app, Response, request

bp = Blueprint('par', __name__)
Flag = None


@bp.route('/execut/shell/<document_id>', methods=['get'])
def execut_shell(document_id):
    p = subprocess.Popen(['bash', '/Users/fanzhenfeng/study/flask-web/app/wget_mirror.sh', document_id],
                            stdout = subprocess.PIPE,
                            stderr = subprocess.STDOUT,
                            text = True
                         )
    # for line in p.stdout:
    #     print(line, end='')
    # rc = p.wait()
    # print('returncode:', rc)
    return jsonify({"status": "success"})


@bp.route('/cookie', methods=['post'])
def getCookie():
    cookies = request.json
    print("获取 cookies 信息：{}".format(cookies))

    return jsonify({"status": "success"})


@bp.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']          # 取表单字段 file
    file.save(file.filename)              # 或自定义路径
    return {'status': 'ok', 'saved_as': file.filename}, 200


@bp.route('/set/<flag>', methods=['get'])
def testFlag(flag):
    global Flag
    Flag = flag
    return Flag


def event_stream():
    count = 0
    while True:
        # 模拟实时数据
        data = f"Server time: {time.ctime()}\n"
        global Flag
        if Flag == 'Y':
            data = "服务器调用客户端执行 ……"
            Flag = 'N'
            yield f"data: {data}\n\n"
        else:
            yield f"data: {data}\n\n"
        # count += 1
        time.sleep(1)  # 每秒发送一次数据


@bp.route('/testsse')
def sse_request():
    return Response(event_stream(), content_type='text/event-stream; charset=utf-8')


@bp.route('/test')
def index():
    # 测试sse
    return """
    <html>
    <head>
        <title>SSE Example</title>
        <script>
            const eventSource = new EventSource('/testsse');
            eventSource.onmessage = function(event) {
                document.getElementById('messages').innerText += event.data + '\\n';
            };
        </script>
    </head>
    <body>
        <h1>Server-Sent Events Example</h1>
        <pre id="messages"></pre>
    </body>
    </html>
    """




